<?php

namespace App\Models;


use App\Http\Common\Lib\Common;
use Illuminate\Support\Facades\Crypt;

class AdminUser extends BaseModel
{
	//
	protected $validatorName = 'AdminUser';

	/**
	 * 用户角色
	 * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
	 */
	public function roles()
	{
		return $this->belongsToMany('App\Models\Role', 'admin_role_relations', 'user_id', 'role_id');
	}

	public function add($input)
	{
		$validateRes = $this->validateData($input, 'add');
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$isUnique = $this->checkUnique('account', $input['account'], [['status', '>', -1]]);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该账号已存在');
		}
		$isUnique = $this->checkUnique('tel', $input['tel'], [['status', '>', -1]]);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该手机已存在');
		}
		$input['salt'] = Common::randomString(6);
		$input['password'] = $this->encryptPwd($input['password'], $input['salt']);
		//$input['password'] = Crypt::encrypt($input['password']);
		unset($input['re_password']);
		//dd($input);
		$user = new AdminUser();
		$user = $user->setData($input);
		$res = $user->save();
		//$id = $this->insertGetId($input);
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), [$this->primaryKey => $user->id]);
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	public function edit($input)
	{
		$scene = 'edit';
		if (!isset($input['password']) || !$input['password']) {
			$scene = 'edit2';
		}
		$validateRes = $this->validateData($input, $scene);
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$isUnique = $this->checkUnique('tel', $input['tel'], [['status', '>', -1], [$this->primaryKey, '<>', $input[$this->primaryKey]]]);
		if (!$isUnique) {
			return Common::dataFormat(config('statusInfo.status.repeated'), '该手机已存在');
		}

		$user = $this->where($this->primaryKey, $input[$this->primaryKey])->where('status', '>', -1)->first();
		if (!$user) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		if (isset($input['password']) && $input['password']) {
			$input['password'] = $this->encryptPwd($input['password'], $user->salt);
			//$input['password'] = Crypt::encrypt($input['password']);
			unset($input['re_password']);
		} else {
			unset($input['password']);
		}
		//dd($input);
		//$user = new AdminUser();
		$user->setData($input);
		$res = $user->save();
		//$id = $this->insertGetId($input);
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	/**
	 * 修改状态
	 * @param $id
	 * @param $opt delete:删除,forbidden:禁用,recovery:正常
	 * @return array
	 */
	public function changeStatus($id, $opt)
	{
		$opts = ['delete', 'forbidden', 'recovery'];
		$opt = strtolower($opt);
		if (!in_array($opt, $opts)) {
			return Common::dataFormat(config('statusInfo.status.fail'), '操作方法不合法');
		}
		$item = $this->where($this->primaryKey, $id)->first();
		if (!$item) {
			return Common::dataFormat(config('statusInfo.status.notFound'), config('statusInfo.msg.notFound'));
		}
		switch ($opt) {
			case 'delete':
				if ($item->id == 1) {
					return Common::dataFormat(config('statusInfo.status.fail'), '无权对超级管理员进行该操作');
				}
				$item->status = -1;
				break;
			case 'forbidden':
				if ($item->id == 1) {
					return Common::dataFormat(config('statusInfo.status.fail'), '无权对超级管理员进行该操作');
				}
				$item->status = 0;
				break;
			case 'recovery':
				$item->status = 1;
				break;
		}
		$res = $item->save();
		if ($res) {
			return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));
		} else {
			return Common::dataFormat(config('statusInfo.status.fail'), config('statusInfo.msg.fail'));
		}
	}

	/**
	 * 保存用户角色设置
	 * @param $id
	 * @param array $roleIds
	 * @return array
	 */
	public function saveRoles($id, $roleIds = [])
	{
		$userInfo = $this->findOne($id);
		if ($userInfo['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($userInfo['status'], $userInfo['msg']);
		}
		$user = $userInfo['data'];
		if (empty($roleIds)) {
			$user->roles()->detach();
		} else {
			$roleIds = array_map('intval', $roleIds);
			$oldRoles = $user->roles;
			$roleModel = new Role();
			$newRoles = $roleModel->whereIn('id', $roleIds)->get();
			$removeRoles = $oldRoles->diff($newRoles);//需要移除的角色
			$addRoles = $newRoles->diff($oldRoles);//需要新增的角色
			//dd([$removeRoles,$addRoles,$newRoles]);
			$removeRoleIds = [];
			$addRoleIds = [];
			foreach ($removeRoles as $removeRole) {
				$removeRoleIds[] = $removeRole->id;
			}
			foreach ($addRoles as $addRole) {
				$addRoleIds[] = $addRole->id;
			}
			if ($removeRoleIds) {
				$user->roles()->detach($removeRoleIds);
			}
			if ($addRoleIds) {
				$user->roles()->attach($addRoleIds);
			}
		}
		return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'));

	}

	/**
	 * 登陆
	 * @param $account
	 * @param $password
	 * @return array
	 */
	public function login($account, $password)
	{
		$input = [
			'account' => $account,
			'password' => $password,
		];
		$validateRes = $this->validateData($input, 'login');
		if ($validateRes['status'] != config('statusInfo.status.success')) {
			return Common::dataFormat($validateRes['status'], $validateRes['msg']);
		}
		$user = $this->where('account', $account)
			->select(['id', 'account', 'nickname', 'sex', 'tel', 'name', 'avatar', 'status', 'password', 'salt'])
			->first();
		if (!$user) {
			return Common::dataFormat(config('statusInfo.status.fail'), '账号或者密码错误');
		}
		//$encryptPwd = Crypt::decrypt($user->password);
		if ($this->encryptPwd($password, $user->salt) != $user->password) {
			return Common::dataFormat(config('statusInfo.status.fail'), '账号或者密码错误!');
		}
		unset($user->password);
		unset($user->salt);
		if ($user->id != 1 && $user->status != 1) {
			return Common::dataFormat(config('statusInfo.status.fail'), '账号状态异常');
		}
		//登陆记录保存
		LoginRecord::saveRecord($user->id, 2);
		return Common::dataFormat(config('statusInfo.status.success'), config('statusInfo.msg.success'), $user);

	}

	/**
	 * 获取管理员可以访问的页面
	 * @param $id
	 * @param int $method 请求方法:0any,1get,2post
	 * @param bool $needChecked
	 * @return array
	 */
	public function getUserUrls($id, $method = 0, $needChecked = true)
	{
		$menuModel = new Menu();
		if (!$needChecked) {
			//不需要权限验证的菜单
			return $menuModel->where('status', 1)->where('is_checked', 0)->get()->pluck('url')->toArray();
		}
		if ($id == 1) {
			//超级管理员
			return $menuModel->where('status', 1)->where('is_checked', 1)->where('method', $method)->get()->pluck('url')->toArray();
		}
		$user = $this->where($this->primaryKey, $id)->where('status', 1)->first();
		if (!$user) {
			return [];
		}
		$roles = $user->roles;
		$menus = [];
		foreach ($roles as $role) {
			$roleMenus = $role->menus()->where('status', 1)->where('is_checked', 1)->where('method', $method)->get()->pluck('url')->toArray();
			$menus = array_merge($menus, $roleMenus);
		}
		$menus = array_unique($menus);
		return $menus;
	}

	/**
	 * 加密密码
	 * @param $password
	 * @param $salt
	 * @return string
	 */
	private function encryptPwd($password, $salt)
	{
		return md5(md5($password) . $salt);
	}

}
